package com.ruoyi.system.outto.goods.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttrTemplateMapper;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttributeMapper;
import com.ruoyi.system.V2.gameAttr.service.IGameAttributeService;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoImgMapper;
import com.ruoyi.system.V2.inter.mapper.ArtRecMapper;
import com.ruoyi.system.interAttr.domain.InterAttr;
import com.ruoyi.system.interAttr.mapper.InterAttrMapper;
import com.ruoyi.system.model.domain.ArtRec;
import com.ruoyi.system.model.domain.GameAttrTemplate;
import com.ruoyi.system.model.domain.GoodsInfoImg;
import com.ruoyi.system.model.domain.SalePartner;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.outto.dto.KghAttribute;
import com.ruoyi.system.outto.dto.KghImg;
import com.ruoyi.system.outto.goods.NEWKANGEHAOAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lz
 * @version 1.0
 * @date 2022/6/5 16:19
 */
@Slf4j
@Service
public class NEWKANGEHAOImpl implements NEWKANGEHAOAPI {

    @Resource
    private IGameAttributeService gameAttributeService;
    @Resource
    InterAttrMapper interAttrMapper;
    @Resource
    private GameAttributeMapper gameAttributeMapper;
    @Resource
    private GoodsInfoImgMapper goodsInfoImgMapper;
    @Resource
    private ArtRecMapper artRecMapper;
    @Resource
    private GameAttrTemplateMapper gameAttrTemplateMapper;

    @Override
    public AjaxResult addGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = params(goodsInfoAndAttrValueDto, "add",salePartner);
        Map<String, Object> canshu = new HashMap<>();
        String uuid = UUID.fastUUID().toString();
        String timestamp = String.valueOf(new Date().getTime() / 1000);
        String md5 = DigestUtils.md5Hex(salePartner.getOther() + salePartner.getSaleKey() + timestamp + uuid).toUpperCase();
        canshu.put("x-kgh-token", salePartner.getOther());
        canshu.put("x-kgh-nonce", uuid);
        canshu.put("x-kgh-signature", md5);
        canshu.put("x-kgh-timestamp", timestamp);
        log.info("看个号添加接口请求参数={}", JSONObject.toJSONString(params));
        String response = HttpUtils.sendPostAddHeader("https://openapi.kangehao.com/publishGoods", JSONObject.toJSONString(params), canshu);
        log.info("看个号添加接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        if (!"SUCCESS".equals(resultJson.getString("code"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
            String kangehaoid = resultJson.getString("data");
            JSONObject jsonObject = JSONObject.parseObject(kangehaoid);
            result.put("outId", jsonObject.getString("guid"));
        }

        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson.getString("msg"));
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult editGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = params(goodsInfoAndAttrValueDto, "edit",salePartner);
        Map<String, Object> canshu = new HashMap<>();
        String uuid = UUID.fastUUID().toString();
        String timestamp = String.valueOf(new Date().getTime() / 1000);
        String md5 = DigestUtils.md5Hex(salePartner.getOther() + salePartner.getSaleKey() + timestamp + uuid).toUpperCase();
        canshu.put("x-kgh-token", salePartner.getOther());
        canshu.put("x-kgh-nonce", uuid);
        canshu.put("x-kgh-signature", md5);
        canshu.put("x-kgh-timestamp", timestamp);
        log.info("看个号编辑接口请求参数={}", JSONObject.toJSONString(params));
        String response = HttpUtils.sendPostAddHeader("https://openapi.kangehao.com/editGoods", JSONObject.toJSONString(params), canshu);
        log.info("看个号编辑接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);

        if (!"SUCCESS".equals(resultJson.getString("code"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
        }

        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson.getString("msg"));
        return AjaxResult.success(result);
    }

    private Map<String, Object> params(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, String type, SalePartner salePartner) {
        Map<String, Object> params = new TreeMap<>();
        String substring = salePartner.getSaleName().substring(salePartner.getSaleName().indexOf("_")+1);
        InterAttr interAttr = interAttrMapper.selectInterAttrByConfig(substring, goodsInfoAndAttrValueDto.getGameId());
        if(StringUtils.isEmpty(interAttr.getServer())){
            throw new GlobalException("该游戏区服暂未匹配,请联系运营人员,游戏名:"+goodsInfoAndAttrValueDto.getGameName());
        }
        if (type.equals("add")) {
            params.put("category_id", Integer.parseInt(interAttr.getInterGameId()));
            params.put("partner_number", goodsInfoAndAttrValueDto.getAccountNumber());
        } else {
            try {
                ArtRec artRecreq = new ArtRec();
                artRecreq.setConfig(salePartner.getId());
                artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
                List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
                params.put("guid", Long.valueOf(artRecs.get(0).getOutid()));
            }catch (Exception e){
                throw new GlobalException("当前账号未推送或三方ID不对!!!"+goodsInfoAndAttrValueDto.getOutId());
            }
        }
        String goods_title = goodsInfoAndAttrValueDto.getDes().length() > 90 ? goodsInfoAndAttrValueDto.getDes().substring(0, 50) : goodsInfoAndAttrValueDto.getDes();
        String goods_describe = goodsInfoAndAttrValueDto.getDes().length() > 300 ? goodsInfoAndAttrValueDto.getDes().substring(0, 299) : goodsInfoAndAttrValueDto.getDes();
        params.put("goods_title",goods_title);
        params.put("goods_describe", goods_describe);
        params.put("price", goodsInfoAndAttrValueDto.getPrice());
        params.put("thumb_url", goodsInfoAndAttrValueDto.getTitleImg());
        List<KghImg> images = new ArrayList<>();
        GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
        goodsInfoImg.setGoodsId(goodsInfoAndAttrValueDto.getId());
        goodsInfoImg.setType(Constants.STR_1);
        List<GoodsInfoImg> infoImgs = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);
        String imgUrls = infoImgs.stream().map(info -> info.getImgUrl()).collect(Collectors.toList()).stream().collect(Collectors.joining(","));
        if (StringUtils.isNotEmpty(imgUrls)) {
            List<String> list = Arrays.asList(imgUrls.split(","));
            if (CollectionUtils.isNotEmpty(list)) {
                for (int i = 0; i < list.size(); i++) {
                    KghImg kghImg = new KghImg();
                    kghImg.setImg_url(list.get(i));
                    kghImg.setThumb_img_url(list.get(i));
                    images.add(kghImg);
                }
            }
        }
        params.put("images", images);

        List<Object> attributes = new ArrayList<>();
        KghAttribute kghAttribute = new KghAttribute();

        //开始匹配属性
        Property(params,goodsInfoAndAttrValueDto,interAttr,attributes,kghAttribute);

        params.put("goods_attribute", attributes);
        return params;
    }

    //参数
    private void Property(Map<String, Object> params, GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, InterAttr interAttr, List<Object> attributes, KghAttribute kghAttribute) {

        //开始匹配区服属性
        builderServer(goodsInfoAndAttrValueDto, params, interAttr.getServer());

        //开始匹配单选属性
        builderRadioAttr(goodsInfoAndAttrValueDto, params, interAttr.getRadioAttr(),attributes,kghAttribute);
        //开始匹配多选属性
        builderCheckAttr(goodsInfoAndAttrValueDto, params, interAttr.getCheckAttr(),attributes,kghAttribute);
        //开始匹配输入框属性
        builderInputAttr(goodsInfoAndAttrValueDto, params, interAttr.getInputAttr(),attributes,kghAttribute);
    }

    /**
     * 开始匹配输入框属性
     *
     * @param goodsInfoAndAttrValueDto
     * @param inputAttr
     */
    private void builderInputAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map<String, Object> params, String inputAttr, List<Object> attributes, KghAttribute kghAttribute) {

        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();

        //========================开始匹配输入框=====================//
        JSONObject jsonObject1 = JSONObject.parseObject(inputAttr);
        String inputJson = jsonObject1.getString("inputJson");
        List<JSONObject> jsonObjects1 = JSONObject.parseArray(inputJson, JSONObject.class);
        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        ArrayList types = new ArrayList<>();
        types.add("number");
        types.add("input");
        gameAttrTemplate.setFieldTypes(types);
        List<GameAttrTemplate> inputTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
        List<JSONObject> defInputObjects = new ArrayList<>();
        defInputObjects.addAll(jsonObjects1);
        for (JSONObject object : jsonObjects1) {
            for (GameAttrTemplate inputTemplate : inputTemplates) {
                JSONObject att = new JSONObject();
                String aavName = inputTemplate.getAavName();
                if (Objects.equals(object.getString("aavName"), inputTemplate.getAavName())) {
                    defInputObjects.remove(object);
                    String aavNameInter = object.getString("interName");
                    Integer interId = object.getInteger("interId");
                    for (Field declaredField : declaredFields) {
                        String name = declaredField.getName();
                        if (Objects.equals(aavName, name)) {
                            declaredField.setAccessible(true);
                            Object o = null;
                            try {
                                o = declaredField.get(goodsInfoAndAttrValueDto);
                            } catch (IllegalAccessException e) {
                                throw new GlobalException("3属性参数错误，请匹配后重新配置");
                            }
                            if(Objects.isNull(o)){
                                String fieldType = inputTemplate.getFieldType();
                                if(fieldType.equals("number")){
                                    o = 0;
                                }
                            }
                            if(Objects.nonNull(o)) {
                                String oneValue = String.valueOf(o);
                                kghAttribute = new KghAttribute();
                                kghAttribute.setAttribute_id(interId);
                                kghAttribute.setOption_value(oneValue);
                                attributes.add(kghAttribute);
                            }
                        }
                    }
                }

            }
        }
        //开始匹配默认值
        for (JSONObject object : defInputObjects) {
            Integer id = object.getInteger("id");
            String defaultValue = object.getString("defaultValue");
            if (StringUtils.isNotEmpty(defaultValue)) {
                kghAttribute = new KghAttribute();
                kghAttribute.setAttribute_id(id);
                kghAttribute.setOption_value(defaultValue);
                attributes.add(kghAttribute);
            }
        }
    }

    private void builderCheckAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map<String, Object> params, String checkAttr, List<Object> attributes, KghAttribute kghAttribute) {
        /**
         * 1、先查询自定义中所有多选的字段
         * 2、再查该账号单选字段中的选项
         * 3、再去接口属性匹配表过滤
         */
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();
        JSONObject checkAttrJson = JSONObject.parseObject(checkAttr);
        String interCheckBoxReqs = checkAttrJson.getString("interCheckBoxReqs");
        List<JSONObject> checkJsonList = JSONObject.parseArray(interCheckBoxReqs, JSONObject.class);
        if (org.springframework.util.CollectionUtils.isEmpty(checkAttrJson)) {
            throw new GlobalException("接口多选属性暂未配置");
        }

        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        List<String> types = new ArrayList<>();
        types.add("checkbox");
        types.add("boxradio");
        gameAttrTemplate.setFieldTypes(types);
        List<GameAttrTemplate> checkAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);

        for (JSONObject object : checkJsonList) {
            String pf_ids = "";
            for (GameAttrTemplate attrTemplate : checkAttrTemplates) {

                String aavName = attrTemplate.getAavName();
                for (Field declaredField : declaredFields) {
                    String name = declaredField.getName();
                    if (aavName.equals(name)) {
                        declaredField.setAccessible(true);

                        Object o = null;
                        try {
                            o = declaredField.get(goodsInfoAndAttrValueDto);
                        } catch (IllegalAccessException e) {
                            throw new GlobalException("多选项" + attrTemplate.getFieldName() + "匹配错误");
                        }
                        String oneValue = String.valueOf(o);
                        String interCheckBoxReqsStr = object.getString("interCheckBoxReqs");
                        //开始匹配二级属性
                        List<JSONObject> jsonObjects2 = JSONObject.parseArray(interCheckBoxReqsStr, JSONObject.class);
                        /**
                         * 咱们的f字段  多选项都是用空格 隔开，用,号切割数组，跟匹配的数据匹配、匹配上说明此账号勾选的有此属性
                         */
                        for (JSONObject jsonObject1 : jsonObjects2) {
                            String[] split1 = oneValue.split(",");
                            String ydConfigId1 = jsonObject1.getString("YdConfigId");
                            if(StringUtils.isNotEmpty(ydConfigId1)) {
                                ydConfigId1 = ydConfigId1.replace(" ","");
                                for (String s : split1) {
                                    if (Objects.equals(s, ydConfigId1)) {
                                        String InterConfigId2 = jsonObject1.getString("id");
                                        pf_ids += "," + InterConfigId2;
                                    }
                                }
                            }
                        }

                    }
                }
            }
            if (StringUtils.isNotEmpty(pf_ids)) {
                kghAttribute = new KghAttribute();
                kghAttribute.setAttribute_id(object.getInteger("id"));
                kghAttribute.setOption_value(pf_ids.substring(1));
                attributes.add(kghAttribute);
            }
        }
    }

    /**
     * 开始匹配单选属性
     *
     * @param goodsInfoAndAttrValueDto
     * @param radioAttr
     */
    private void builderRadioAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map<String, Object> params, String radioAttr, List<Object> attributes, KghAttribute kghAttribute) {
        //========================开始匹配单选属性=====================//
        JSONObject jsonObject = JSONObject.parseObject(radioAttr);
        String interRadioReqs = jsonObject.getString("interRadioReqs");
        log.info(JSONObject.toJSONString(interRadioReqs));
        List<JSONObject> jsonObjects = JSONObject.parseArray(interRadioReqs, JSONObject.class);
        if (!org.springframework.util.CollectionUtils.isEmpty(jsonObjects)) {
            /**
             * 1、先查询自定义中所有单选的字段
             * 2、再查该账号单选字段中的选项
             * 3、再去接口属性匹配表过滤
             */
            GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
            gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
            gameAttrTemplate.setIsEnable("0");
            gameAttrTemplate.setFieldType("radio");
            List<GameAttrTemplate> gameAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
            Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();

            List<JSONObject> defObjects = new ArrayList<>();
            defObjects.addAll(jsonObjects);
            for (JSONObject object : jsonObjects) {
                for (GameAttrTemplate attrTemplate : gameAttrTemplates) {
                    JSONObject att = new JSONObject();
                    String aavName = attrTemplate.getAavName();
                    for (Field declaredField : declaredFields) {
                        String name = declaredField.getName();
                        if (aavName.equals(name)) {
                            //一级属性
                            //注意 YdConfigId 对应的是 f字段对应的 id
                            if (Objects.equals(object.getLong("YdConfigId"), attrTemplate.getId())) {
                                String id = object.getString("id");
                                defObjects.remove(object);//如果匹配上，则去掉
                                String interRadioReqs1 = object.getString("interRadioReqs");
                                List<JSONObject> jsonObjects2 = JSONObject.parseArray(interRadioReqs1, JSONObject.class);
                                declaredField.setAccessible(true);
                                try {
                                    //获取选择的值 例如  实名中的可二次
                                    Object o = declaredField.get(goodsInfoAndAttrValueDto);
                                    String oneValue = String.valueOf(o);
                                    List<JSONObject> twoAttr = jsonObjects2.stream().filter(j -> StringUtils.isNotEmpty(j.getString("YdConfigId"))?j.getString("YdConfigId").contains(oneValue):"111".contains(oneValue)).collect(Collectors.toList());
                                    String interConfigName = object.getString("InterConfigName");
                                    String defaultValue = object.getString("defaultValue");
                                    if (org.springframework.util.CollectionUtils.isEmpty(twoAttr)) {
                                        if (StringUtils.isNotEmpty(defaultValue)) {
                                            kghAttribute.setAttribute_id(Integer.parseInt(id));
                                            kghAttribute.setOption_value(defaultValue);
                                            attributes.add(kghAttribute);
                                        }
                                    }
//                                if (org.springframework.util.CollectionUtils.isEmpty(twoAttr) && StringUtils.isEmpty(defaultValue)) {
//                                    throw new GlobalException("属性" + interConfigName + " 接口要求必传，但是暂未匹配到，请设置默认值");
//                                }
                                    if (!org.springframework.util.CollectionUtils.isEmpty(twoAttr)) {
                                        kghAttribute = new KghAttribute();
                                        JSONObject jsonObject2 = twoAttr.get(0);
                                        String interConfigId2 = jsonObject2.getString("InterConfigId");
                                        kghAttribute.setAttribute_id(Integer.parseInt(id));
                                        kghAttribute.setOption_value(interConfigId2);
                                        attributes.add(kghAttribute);
                                    }
                                } catch (Exception e) {
                                    throw new GlobalException("单选项" + attrTemplate.getFieldName() + "匹配错误");
                                }
                            }
                        }
                    }
                }
            }
            //开始匹配默认值
            for (JSONObject object : defObjects) {
                String id = object.getString("id");
                interRadioReqs = object.getString("interRadioReqs");
                jsonObjects = JSONObject.parseArray(interRadioReqs, JSONObject.class);
                for (JSONObject objects : jsonObjects) {
                    if(StringUtils.isNotEmpty(objects.getString("defaultValue"))){
                        kghAttribute = new KghAttribute();
                        kghAttribute.setAttribute_id(Integer.parseInt(id));
                        kghAttribute.setOption_value(objects.getString("defaultValue"));
                        attributes.add(kghAttribute);
                    }
                }
            }
            //========================单选属性匹配结束=====================//
        }
    }

    private void builderServer(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map params, String server) {
        //========================开始匹配区服属性=====================//
        JSONObject jsonObject = JSONObject.parseObject(server);
        //开始匹配一级区服
        String interServeReqs = jsonObject.getString("interServeReqs");
        String qufuid = "";
        JSONObject oneServerJson = new JSONObject();
        if (Objects.equals(goodsInfoAndAttrValueDto.getGameType(), "0")) {
            qufuid = goodsInfoAndAttrValueDto.getSystemId() + "" + goodsInfoAndAttrValueDto.getCarrierId() + "";
            List<JSONObject> oneServer = JSONObject.parseArray(interServeReqs, JSONObject.class);
            for (JSONObject object : oneServer) {
                String ydServeId = object.getString("YdServeId");
                if (StringUtils.isNotEmpty(ydServeId)) {
                    ydServeId = ydServeId.replace(",", "").replace(" ", "");
                    if (qufuid.contains(ydServeId)) {
                        oneServerJson = object;
                        params.put("client_id", oneServerJson.getInteger("id"));
                        break;
                    }
                }
            }
        } else {
            qufuid = goodsInfoAndAttrValueDto.getServerId() + "";
            List<JSONObject> oneServer = JSONObject.parseArray(interServeReqs, JSONObject.class);
            for (JSONObject object : oneServer) {
                String ydServeId = object.getString("YdServeId");
                if (StringUtils.isNotEmpty(ydServeId)) {
                    String interServerRes = object.getString("interServerRes");
                    List<JSONObject> oneServers = JSONObject.parseArray(interServerRes, JSONObject.class);
                    if(CollectionUtils.isNotEmpty(oneServers)){
                        for (JSONObject objects : oneServers) {
                            ydServeId = objects.getString("YdServeId");
                            ydServeId = ydServeId.replace(",", "").replace(" ", "");
                            if (Objects.equals(qufuid, ydServeId)) {
                                oneServerJson = objects;
                                params.put("client_id", object.getInteger("id"));
                                params.put("server_id", oneServerJson.getInteger("id"));
                                break;
                            }
                        }
                    }else {
                        if(goodsInfoAndAttrValueDto.getGroupId().toString().equals(ydServeId)) {
                            params.put("client_id", object.getInteger("id"));
                        }
                    }
                }
            }
        }
    }

    @Override
    public AjaxResult delGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Map<String, Object> canshu = new HashMap<>();
        String uuid = UUID.fastUUID().toString();
        String timestamp = String.valueOf(new Date().getTime() / 1000);
        String md5 = DigestUtils.md5Hex(salePartner.getOther() + salePartner.getSaleKey() + timestamp + uuid).toUpperCase();
        canshu.put("x-kgh-token", salePartner.getOther());
        canshu.put("x-kgh-nonce", uuid);
        canshu.put("x-kgh-signature", md5);
        canshu.put("x-kgh-timestamp", timestamp);
        Map<String, Object> params = new HashMap<>();
        ArtRec artRecreq = new ArtRec();
        artRecreq.setConfig(salePartner.getId());
        artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
        List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
        params.put("guid", Long.valueOf(artRecs.get(0).getOutid()));
        log.info("看个号删除接口请求参数={}", JSONObject.toJSONString(params));
        String response = HttpUtils.sendPostAddHeader("https://openapi.kangehao.com/removeGoods", JSONObject.toJSONString(params), canshu);
        if (StringUtils.isEmpty(response)) {
            throw new GlobalException("请求接口失败");
        }
        log.info("看个号删除接口返回参数={}", JSONObject.toJSONString(response));
        JSONObject resultJson = JSONObject.parseObject(response);
        Map<String, Object> result = new HashMap<>();

        if (!"SUCCESS".equals(resultJson.getString("code"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
        }

        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson.getString("msg"));
        return AjaxResult.success(result);
    }


    public static void main(String[] args) {
        Map<String, Object> sign = getSign();
        String games = attrs(sign.get("nonce").toString(), sign.get("timestamp").toString(), sign.get("signature").toString(),sign.get("token").toString());
        System.out.println(games);
    }

    static String games(String nonce,String Timestamp,String Signature,String Token){
        String url = "https://test.kangehao.com/categoryInfo";
        String body = HttpRequest.post(url).header("x-kgh-token", Token).header("x-kgh-nonce", nonce).header("x-kgh-signature", Signature).header("x-kgh-timestamp", Timestamp)
                .execute().body();
        return body;
    }
    static String areas(String nonce,String Timestamp,String Signature,String Token){
        String url = "https://test.kangehao.com/areaInfo";
        Map<String,Object> params = new HashMap<>();
        params.put("category_id",6);
        String body = HttpRequest.post(url).header("x-kgh-token", Token).header("x-kgh-nonce", nonce)
                .header("x-kgh-signature", Signature).header("x-kgh-timestamp", Timestamp).body(JSONObject.toJSONString(params))
                .execute().body();
        return body;
    }
    static String attrs(String nonce,String Timestamp,String Signature,String Token){
        String url = "https://test.kangehao.com/categoryAttribute";
        Map<String,Object> params = new HashMap<>();
        params.put("category_id",6);
        String body = HttpRequest.post(url).header("x-kgh-token", Token).header("x-kgh-nonce", nonce)
                .header("x-kgh-signature", Signature).header("x-kgh-timestamp", Timestamp).body(JSONObject.toJSONString(params))
                .execute().body();
        return body;
    }
    static Map<String,Object> getSign(){
        Map<String,Object> signMap = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        params.put("x-kgh-token", "2023022452790594");
        params.put("x-kgh-nonce", UUID.fastUUID().toString());
        params.put("x-kgh-signature", DigestUtils.md5Hex("2023022452790594" + "f220a3b4619e39cbc40c5f1f1c7b6344" + new Date().getTime() / 1000 + "" + UUID.fastUUID().toString()).toUpperCase());
        params.put("x-kgh-timestamp", String.valueOf(new Date().getTime() / 1000));
        String response = HttpUtils.sendPost("https://test.kangehao.com/login", JSONObject.toJSONString(params), "application/json");
        String data = JSONObject.parseObject(response).getString("data");
        String nonce = JSONObject.parseObject(data).getString("Nonce");
        String Timestamp = JSONObject.parseObject(data).getString("Timestamp");
        String Signature = JSONObject.parseObject(data).getString("Signature");
        String Token = JSONObject.parseObject(data).getString("Token");
        signMap.put("nonce",nonce);
        signMap.put("timestamp",Timestamp);
        signMap.put("signature",Signature);
        signMap.put("token",Token);
        return signMap;
    }

}
